<template>
<van-address-list
  class="address-views"
  v-model="chosenAddressId"
  :list="pager"
  @add="onAdd"
  @edit="onEdit"
/>
</template>

<script>
import { AddressList } from 'vant';
import ajaxVant from '../../../utils/ajaxVant';
import auth from '../../../utils/auth';
import areaList from '../../../mock/area';

export default {
  components: {
    [AddressList.name]: AddressList
  },
  data() {
    return {
      chosenAddressId: '0',
      pager: []
    };
  },
  methods: {
    getData() {
      var _this = this;
      auth.getToken().then(function(token) {
        ajaxVant.get('/user/address?token=' + token).then(function(data) {
          if (data !== false) {
            for (var i in data.pager) {
              let address = areaList['province_list'][data.pager[i].area_code.substring(0, 2) + '0000'];
              address += areaList['city_list'][data.pager[i].area_code.substring(0, 4) + '00'];
              address += areaList['county_list'][data.pager[i].area_code];
              address += data.pager[i].address_detail;

              _this.pager.push({
                id: data.pager[i].address_id,
                name: data.pager[i].name,
                tel: data.pager[i].tel,
                address: address
              });

              if (data.pager[i].is_default.toString() === '1') {
                _this.chosenAddressId = data.pager[i].address_id;
              }
            }
          }
        });
      });
    },
    onAdd() {
      this.$router.push({ name: 'userAddressCreate' });
    },
    onEdit(address) {
      this.$router.push({ name: 'userAddressUpdate', params: { id: address.id }});
    }
  },
  mounted() {
    this.getData();
  }
};
</script>

<style>
.address-views .van-address-list__add {
  bottom: 48px;
}
</style>